package arraylistTest;

import java.util.Arrays;

public class MyArrayList {

    private int [] elem;
    private int usedSize;   //已使用容量大小
    public MyArrayList(){
        this.elem = new int[10];
    }


    public  MyArrayList(int initCapacity) { //指定容量大小
        this.elem = new int[initCapacity];
    }
    //打印数组元素
    public void display(){
        for(int i = 0; i < this.usedSize; i++){
            System.out.println(this.elem[i]);
        }
    }
    //普通插入
    public void add(int x){
        //判断数组是否满
        if(isFull()){
            this.elem = Arrays.copyOf(this.elem,this.elem.length * 2);
        }
        this.elem[this.usedSize] = x;
        this.usedSize++;
    }
    //按数组下标插入
    public void add(int pos, int data){
        //pos位置合法性的判断
        check(pos);
        if(isFull()){
            this.elem = Arrays.copyOf(this.elem, this.elem.length * 2);
        }
        for(int i = this.usedSize; i > pos; i--){
            elem[i] = elem[i-1];
        }
        elem[pos] = data;
        this.usedSize++;
    }

    /**
     * 数组是否满
     * @return
     */
    private boolean isFull(){
        if(this.usedSize == this.elem.length){
            return true;
        }
        return false;
    }

    /**
     * 检查下标位置是否合法
     * @param pos
     */
    private void check(int pos){
        if(pos < 0 || pos > this.usedSize){
            throw new PosOutOfBoundsException("位置不合法");
        }
    }
    //是否包含某个元素
    public boolean contains(int toFind){
        for(int i = 0; i < this.usedSize; i++){
            if(this.elem[i] == toFind){
                return true;
            }
        }
        return false;
    }
    //查找某个元素并返回元素下标
    public int indexOf(int toFind){
        for(int i = 0; i < this.usedSize; i++){
            if(this.elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }
    //获取pos位置的元素
    public int get(int pos){
        check(pos);
        return this.elem[pos];
    }
    //给 pos 位置的元素设为 value [更新]
    public void set(int pos,int data){
        check(pos);
        this.elem[pos] = data;
    }
    //获取顺序表长度
    public int getSize(){
        return this.usedSize;
    }
    //删除数组元素
    public void remove(int toRemove) {
        //检查是否有该元素
        int pos = indexOf(toRemove);
        if(pos == -1){
            System.out.println("没有该元素");
        }
        for(int i = pos; i < this.usedSize - 1; i++){
            this.elem[i] = this.elem[i+1];
        }
        this.usedSize--;
    }
    public void clear(){
        this.usedSize = 0;
        //若为引用类型则应将每一个元素位置的引用置为空
        /*for(int i = 0; i < this.usedSize; i++){
            this.elem[i] = null;
        }*/
    }
}
